package com.snail.readyvr.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.snail.readyvr.R;
import com.snail.readyvr.glide.GlideUtils;
import com.snail.readyvr.ui.RoundedImageView;
import com.snail.readyvr.util.DialogUtils;
import com.snail.readyvr.util.Utils;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

import party.loveit.download.core.DLInfo;
import party.loveit.download.core.DLManager;
import party.loveit.download.core.DLStates;
import party.loveit.swipemenu.core.SwipeHorizontalMenuLayout;

/**
 * Created by MRKING on 2017/1/11.
 */

public class DownloadingAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {

    private Context mContext;
    private int mLayoutId;
    private List<DLInfo> mDLInfos;
    private ConcurrentHashMap<String, ProgressBar> progressBars;
    private ConcurrentHashMap<String, TextView> speedTexts;
    private RecyclerView mRecyclerView;

    public DownloadingAdapter(Context context, int layoutId, RecyclerView recyclerView) {
        mContext = context;
        mLayoutId = layoutId;
        mRecyclerView = recyclerView;
        mDLInfos = new Vector<>();
        progressBars = new ConcurrentHashMap<>();
        speedTexts = new ConcurrentHashMap<>();
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return RecyclerViewHolder.get(mContext, parent, mLayoutId);
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        final DLInfo info = mDLInfos.get(position);
        RoundedImageView roundedImageView = holder.getView(R.id.downloading_img);
        GlideUtils.loadRoundImg(mContext, info.imgUrl, roundedImageView);

        holder.setText(R.id.downloading_video_name, info.videoName)
                .setText(R.id.downloaded_video_length, Utils.formatVideoLength(info.totalBytes))
                .setText(R.id.downloaded_video_length2, Utils.formatVideoLength(info.totalBytes))
                .setText(R.id.downloaded_video_speed, info.speed + "," + (info.currentBytes / info.totalBytes) * 100 + "%");
        TextView stateText = holder.getView(R.id.downloaded_video_state_text);
        ImageView stateImg = holder.getView(R.id.downloading_state);
        stateImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(info.dlState == DLStates.DL_DLING)
                    DLManager.getInstance().dlStop(info.baseUrl);
                else
                    DLManager.getInstance().dlStart(info.baseUrl);
            }
        });

        LinearLayout notDownloadLayout = holder.getView(R.id.downloading_not_download_layout);
        notDownloadLayout.setVisibility(info.dlState == DLStates.DL_DLING ? View.GONE : View.VISIBLE);
        LinearLayout downloadLayout = holder.getView(R.id.downloading_download_layout);
        downloadLayout.setVisibility(info.dlState == DLStates.DL_DLING ? View.VISIBLE : View.GONE);
        if (info.dlState == DLStates.DL_DLING) {
            progressBars.put(info.baseUrl, (ProgressBar) holder.getView(R.id.downloaded_video_progress));
            speedTexts.put(info.baseUrl, (TextView) holder.getView(R.id.downloaded_video_speed));
            stateImg.setBackgroundResource(R.drawable.pasue_download_btn_selector);
        } else if (info.dlState == DLStates.DL_ERROR) {
            stateImg.setBackgroundResource(R.drawable.re_download_btn_selector);
            stateText.setText(R.string.download_error_state);
        } else {
            stateImg.setBackgroundResource(R.drawable.start_download_btn_selector);
            stateText.setText(R.string.download_pause_state);
        }
        stateText.setTextColor(info.dlState == DLStates.DL_ERROR ? mContext.getResources().getColor(R.color.download_cancel_bg_color) : mContext.getResources().getColor(R.color.indicator_title_selected_color));

        final SwipeHorizontalMenuLayout swipeHorizontalMenuLayout = holder.getView(R.id.downloading_swipe_menu);
        swipeHorizontalMenuLayout.smoothCloseMenu();
        holder.setOnClickListener(R.id.smMenuViewRight, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swipeHorizontalMenuLayout.smoothCloseMenu();
                DialogUtils.showDownloadDialog((Activity) mContext, mContext.getString(R.string.download_dialog_title), mContext.getString(R.string.downloading_dialog_content), mContext.getString(R.string.downloading_dialog_cancel), mContext.getString(R.string.downloading_cancel), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteItem(info.baseUrl);
                        DLManager.getInstance().dlCancel(info.baseUrl);
                    }
                });
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDLInfos.size();
    }

    public void addDatas(List<DLInfo> data) {
        mDLInfos.addAll(data);
        notifyDataSetChanged();
    }

    public synchronized void itemChangedState(String url) {
        int position = getPosition(url);
        if (position == -1)
            return;
        notifyItemChanged(position);
    }

    public void deleteItem(String url) {
        int position = getPosition(url);
        if (position == -1)
            return;
        mDLInfos.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, mDLInfos.size());
    }

    public void changeProgress(String url) {
        if (mRecyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE)
            return;
        int position = getPosition(url);
        if (position == -1)
            return;
        LinearLayoutManager manager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        if (manager.findFirstVisibleItemPosition() <= position && position <= manager.findLastVisibleItemPosition()) {
            DLInfo info = getDLInfo(url);
            if (info != null && progressBars.containsKey(url) && speedTexts.containsKey(url)) {
                progressBars.get(url).setMax((int) info.totalBytes);
                progressBars.get(url).setProgress((int) info.currentBytes);
                speedTexts.get(url).setText(info.speed + ", " + (int)(((double)info.currentBytes / (double)info.totalBytes) * 100) + "%");
            }
        }
    }

    private DLInfo getDLInfo(String url) {
        if (url == null)
            return null;
        synchronized (mDLInfos) {
            for (DLInfo info : mDLInfos) {
                if (info.baseUrl.equals(url))
                    return info;
            }
        }
        return null;
    }

    private int getPosition(String url) {
        if (url == null)
            return -1;
        synchronized (mDLInfos) {

            for (int i = 0; i < mDLInfos.size(); i++) {
                if (mDLInfos.get(i).baseUrl.equals(url))
                    return i;
            }
        }
        return -1;
    }

}
